<template>
  <view class="content">
    <view class="logo-layout" :style="{height: `${globalData.navBarHeight}px`}">
      <view class="logo"></view>
    </view>
    <view class="map"
      :style="{ paddingTop: `${globalData.navBarHeight}px`, height: showMarkerDialog ? '90vh' : mapHeight }">
      <map style="width: 100%; height: 100%" :latitude="latitude" :longitude="longitude" :markers="markers"
        @tap="mapTap" @regionchange="regionchange" :scale="scale" :min-scale="minScale" :max-scale="maxScale"
        @markertap.stop="markertap" :enable-scroll="showCouponDialog ? false : true">
<!--        <view class="unfinish-order" @click="uptoOrder" v-if="showOrderToken()">
          <view class="icon">
            <image src="../../static/images/order.png" mode=""></image>
          </view>
          <view class="order" >
            <text>您还有1个未完成的订单</text>
            <image src="../../static/images/right.png" mode=""></image>
          </view>
        </view> -->
        <view class="floated">
          <view class="customer"></view>
          <view class="search" @click="chooseAddress"></view>
          <view class="position" @click="getlocations"></view>
        </view>
      </map>
    </view>
    <view class="menu" v-show="!showMarkerDialog">
      <view class="menu-part">
        <view class="menu-one" @click="uptoShop">
          <span>
            <image src="../../static/images/shop.png"></image>
          </span>
          <text>附近门店</text>
        </view>
        <view class="menu-button">
          <van-button @click="scanCode" color="linear-gradient(#0366E0, #1E50DC)" type="info">
            <image src="../../static/images/scon.png" mode=""></image>
            扫码充电
          </van-button>
          <!--          <button @click="scanCode">
            <image src="../../static/images/scon.png" mode=""></image>
            扫码充电
          </button> -->
        </view>
        <view class="menu-one" @click="uptoPersonal">
          <span>
            <image src="../../static/images/user.png" mode=""></image>
          </span>
          <text>个人中心</text>
        </view>
      </view>
    </view>
    <van-toast id="van-toast" />
    <!-- 闪电标显示位置信息弹窗 -->
    <van-dialog custom-style="top: 80% !important; width: 90%;" :overlay="false" :show-confirm-button="false" use-slot
      :show="showMarkerDialog" @close="showMarkerDialog = false">
      <markerDialog :distance="distance" :locationInfo="locationInfo" />
    </van-dialog>

    <!-- 未完成订单弹窗 -->
    <van-dialog class="unfinishOrder"
      custom-style="top: 50% !important; left: 50%; width: 260px; transform: translate(-50%, -50%); border-radius: 10px;"
      :show-confirm-button="false" use-slot :show="showOrder" @close="showOrder = false">
      <unfinishOrder :dialogType="dialogType" :title="dialogTitle" :infoText="infoText"
        @handleCancel="showOrder = false" />
    </van-dialog>

    <!-- 优惠券弹窗 -->
    <couponDialog class="couponDialog" :class="{ hidden: !showCouponDialog }" v-if="showCouponDialog"
      @getCoupon="getCoupon" :showCouponDialog="showCouponDialog" @closeCouponDialog="closeCouponDialog" />

    <!-- 授权获取昵称和头像 -->
    <!-- <empowerDialog class="empower" :showSheet="showSheet" @handleCancel="showSheet = false" @handleSave="handleSave" /> -->
  </view>
</template>

<script>
  let tencentMapApi = 'https://apis.map.qq.com/ws/distance/v1/matrix?'
  let key = 'ECFBZ-QRS6C-ZAE2O-ATNJT-WQENH-DOFOP'
  let QQMapWX = require('@/utils/qqmap-wx-jssdk.min.js');
  import markerDialog from '@/component/markerDialog.vue'
  import couponDialog from '@/component/couponDialog.vue'
  import axios from 'axios'
  import Toast from '@/wxcomponents/vant/toast/toast';
  import unfinishOrder from '@/component/unfinishOrder.vue'
  import {
    mapGetters
  } from 'vuex'
  import {
    getUserMobile
  } from '@/api/login'
  import { hasDeposit } from '@/api/order'
  import {
    checkBeginnerCoupon,
    clickCoupon
  } from '@/api/user'
  import {
    hasToken
  } from '@/utils/token.js'
  import {
    getCouponInfo
  } from '@/api/user.js'
  import {
    getShopList
  } from '@/api/shop.js'
  export default {
    data() {
      return {
        title: 'Hello',
        globalData: {
          navBarHeight: 0, // 导航栏高度
          menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
          menuTop: 0, // 胶囊距底部间距（保持底部间距一致）
          menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）
        },
        address: '',
        // scale:
        scale: 15, // 17
        minScale: 3, // 最小缩放级别
        maxScale: 20, // 最大缩放级别
        latitude: 39.909,
        longitude: 116.39742,
        markers: [],
        circles: [{
          color: '#fff',
          fillColor: '#000'
        }],
        showOrder: false, // 显示订单未完成
        showMarkerDialog: false, // 显示锚点弹窗信息
        showOrderState: false, // 显示订单提示弹窗
        mapHeight: '',
        markerDialogInfo: {},
        markerInfo: {},
        locationInfo: {},
        dialogType: 'unfinishOrder', // 弹窗类型
        dialogTitle: '提示', // 弹窗标题
        infoText: '您有未完成订单，需将上一笔订单结束后方可再次租借！', // 弹窗文案
        distance: '', // 传距离
        showCouponDialog: false, // 显示优惠券弹窗
        showSheet: false // 显示授权sheet
      }
    },
    components: {
      markerDialog,
      unfinishOrder,
      couponDialog
    },
    computed: {
      ...mapGetters(['userInfo', 'token']),
    },
    watch: {
      token(newVal) {
        if (newVal) {
          this.getLocation()
        }
      },
      userInfo(newVal) {
        if (newVal.newComeCouponNotPick) {
          setTimeout(() => {
            this.showCouponDialog = newVal.newComeCouponNotPick
          }, 2000)
        }
      },
      deep: true
    },
    onLoad() {
      // this.showSheet = true
      // this.showCouponDialog = true
      // this.showOrder = true
      this.getInitLogoHeight() // 自适应导航栏logo高度
      if (!hasToken()) this.autoLogin() // 没有token调用自动登录
      this.getLocation()
      this.getCouponList()
    },
    onReady() {
      this.calculateMapHeight() // 自适应地图高度
    },
    methods: {
      getDistance(distance) {
        if (distance >= 1000) {
          return (distance / 1000).toFixed(1) + 'km';
        } else {
          return distance + 'm';
        }
      },
      showOrderToken() {
        if (hasToken()) {
          return true
          // this.showOrder = true
        }
      },
      // 查询是否领取新人优惠券
      async checkBeginnerCoupon() {
        if (hasToken()) {
          setTimeout(() => {
            this.showCouponDialog = true
          }, 2000)
        }
      },
      // 查询账户下的优惠券
      async getCouponList() {

        if (hasToken()) {
          const data = await getCouponInfo(this.userInfo.userId)
          console.log(data);
        }
      },
      // 自动登录
      autoLogin() {
        if (this.$refs['showSheet']) this.$refs['showSheet'].showSheet = true
      },
      // 关闭优惠券弹窗
      closeCouponDialog() {
        this.showCouponDialog = false
      },
      getInitLogoHeight() {
        const that = this;
        // 获取系统信息
        const systemInfo = wx.getSystemInfoSync();
        // 胶囊按钮位置信息
        const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
        // 导航栏高度 = 状态栏高度 + 44
        that.globalData.navBarHeight = systemInfo.statusBarHeight + 44;
        that.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
        that.globalData.menuTop = menuButtonInfo.top;
        that.globalData.menuHeight = menuButtonInfo.height;
      },
      calculateMapHeight() {
        // 获取设备信息
        const systemInfo = uni.getSystemInfoSync();
        const windowHeight = systemInfo.windowHeight;
        // 设计稿中地图的高度和设计稿的高度
        const designMapHeight = 590; // 设计稿中地图的高度
        const designHeight = 812; // 设计稿的高度
        // 计算地图在当前设备上的高度
        let mapHeight = windowHeight * (designMapHeight / designHeight);

        const percentage = ((windowHeight - mapHeight) / windowHeight) * 100;
        // 将百分比与mapHeight相加
        const finalHeight = mapHeight + percentage;
        // 将地图高度设置为实例属性
        if (windowHeight > 844 && !this.showMarkerDialog) {
          this.mapHeight = `${finalHeight}px`;
        } else if (this.showMarkerDialog) {
          this.mapHeight = `90vh`;
        } else {
          this.mapHeight = `${mapHeight}px`;
        }
        return mapHeight + 'px'
      },
      // 获取当前位置
      getLocation(type, lat, long) {
        //获取当前的地理位置
        let vthis = this;
        wx.getLocation({
          type: 'gcj02',
          success: async function(res) {
            vthis.latitude = type === 0 ? lat : res.latitude;
            vthis.longitude = type === 0 ? long : res.longitude;
            vthis.markers = [{
              id: 0,
              latitude: type === 0 ? lat : res.latitude,
              longitude: type === 0 ? long : res.longitude,
              iconPath: '../../static/images/located.png',
              width: 21,
              height: 39
            }];
            if (hasToken()) {
              const data = await getShopList({
                pageNum: 1, //页码
                pageSize: 10, //每页显示
              }, {
                currentLongitude: vthis.longitude,
                currentLatitude: vthis.latitude,
                meter: 10000
              })
              // 调用接口
              let shopList = []
              shopList = data.rows.map((item, index) => {
                return {
                  id: item.storeId,
                  latitude: item.storeLatitude,
                  longitude: item.storeLongitude,
                  titles: item.storeName,
                  address: item.storeDetailAddress,
                  iconPath: '../../static/images/power.png',
                  storeImg: item.storeImg,
                  storeStartTime: item.storeStartTime,
                  storeEndTime: item.storeEndTime,
                  storeStatus: item.storeStatus,
                  distance: item.distance,
                  width: 30,
                  height: 30
                }
              })
              vthis.markers = [...vthis.markers, ...shopList]
            }
          },
          fail: function(res) {
            console.log(res);
          }
        });
      },
      async markertap(e) {
        if (!hasToken()) {
          if (this.$refs['showSheet']) this.$refs['showSheet'].showSheet = true
          return
        }
        if (this.showCouponDialog || this.showSheet) return
        if (e.markerId <= 0) return
        this.markers.forEach(item => {
          if (item.id === 0) {
            item.width = 21;
            item.height = 39;
          } else {
            item.width = 30,
              item.height = 30
          }
          delete item.label
        })
        const to = this.$_.find(this.markers, {
          id: e.markerId
        })
        this.longitude = to.longitude
        this.latitude = to.latitude
        setTimeout(() => {
          for (const item of this.markers) {
            if (item.id === e.markerId && item.id !== 0) {
              this.$nextTick(function() {
                setTimeout(() => {
                  item.width = 42,
                    item.height = 42
                }, 0)
              })
              let anchorX = 0; // 默认值
              let anchorY = -72
              // 获取设备信息
              const systemInfo = uni.getSystemInfoSync();
              if (systemInfo.platform === 'android') {
                anchorX = -32; // 如果是安卓设备，设置为 -40
                anchorY = -75
              }
              item.label = {
                content: `约${this.getDistance(item.distance)}`,
                anchorX,
                anchorY,
                color: '#fff',
                fontSize: '12px',
                bgColor: '#1d3030',
                textAlign: 'center',
                borderRadius: 50,
                padding: 8
              }
              this.locationInfo = item
              this.distance = item.distance
            }
          }
          this.markerInfo = e
          this.showMarkerDialog = true
        }, 100)
      },
      mapTap(e) {
        this.regionchange()
      },
      regionchange(e) {
        if (e && e.type === 'end' && e.causedBy === "drag") {
          this.latitude = e.detail.centerLocation.latitude
          this.longitude = e.detail.centerLocation.longitude
        }
        this.markers.forEach(item => {
          if (item.id === 0) {
            item.width = 21,
              item.height = 39
          } else {
            item.width = 30,
              item.height = 30
          }
          delete item.label
          this.showMarkerDialog = false
          this.markerInfo = {}
        })
      },
      chooseAddress() {
        if (!hasToken()) {
          if (this.$refs['showSheet']) this.$refs['showSheet'].showSheet = true
          return
        }
        uni.chooseLocation({
          success: (res) => {
            this.getLocation(0, res.latitude, res.longitude)
          }
        })
      },
      // 领取优惠券
      async getCoupon() {
        const data = await clickCoupon()
        if (data.code === 200) {
          uni.showToast({
            title: '领取成功'
          })
        }
        // this.showSheet = true
      },
      // 授权头像昵称，提交
      async handleSave(userInfo) {
        this.$store.dispatch('user/login', userInfo)
      },
      getlocations() {
        setTimeout(() => {
          this.getLocation()
        }, 100)
      },
      // 附近门店
      uptoShop() {
        uni.navigateTo({
          url: '/subpkg/nextShop/index'
        })
      },
      // 个人中心
      uptoPersonal() {
        uni.navigateTo({
          url: '/subpkg/personalCenter/index'
        })
      },
      // 订单详情
      uptoOrder() {
        // uni.navigateTo({
        //   url: '/subpkg/payDeposit/index'
        // })
        uni.navigateTo({
          url: '/subpkg/orderInfo/index'
        })
      },
      async scanCode() {
        // uni.navigateTo({
        //   url: '/subpkg/powerbankInfo/index'
        // })
        if (!hasToken()) {
          if (this.$refs['showSheet']) this.$refs['showSheet'].showSheet = true
          return
        }
        const data = await hasDeposit({})
        // console.log(data);
        // const roles = this.userInfo.roles.find(item => item.roleId)
        if (data.data) {
          uni.navigateTo({
            url: '/subpkg/powerbankInfo/index'
          })
        } else {
          uni.navigateTo({
            url: '/subpkg/payDeposit/index?lastPath=home'
          })
        }
        // uni.scanCode({
        //   success: (res) => {
        //     uni.navigateTo({
        //       url: '/subpkg/powerbankInfo/index'
        //     })
        //   }
        // })
      }
    }
  }
</script>

<style lang="less" scoped>
  .content {
    height: 100vh;
    /* 设置容器高度，这里使用视窗高度作为示例 */
    background: url(@/static/images/home-banner.png) 0 0 no-repeat;
    background-size: contain;
    background-color: #f7f7f7 !important;
    width: 100%;

    .unfinishOrder {
      ::v-deep .van-button--primary {
        flex: 1;
        border-radius: 10px;
        font-size: 15px;
      }

      ::v-deep .van-button--normal {
        border-radius: 10px;
        font-size: 15px;
      }

      ::v-deep .van-button {
        width: 100%;
      }
    }

    .logo-layout {
      position: fixed;
      display: flex;
      align-items: flex-end;
      padding: 0 15px;
      margin-bottom: 2px;
      box-sizing: border-box;
      z-index: 999;

      .logo {
        width: 107px;
        height: 35px;
        background: url(../../static/images/logo.png) 0 0 no-repeat;
        background-size: contain;
      }
    }

    .map {
      position: absolute;
      left: 0;
      right: 0;
      margin: 0 10px;
      z-index: 1;
      border-radius: 10px;

      .unfinish-order {
        position: absolute;
        top: 15px;
        left: 15px;
        right: 15px;
        background-color: #F1F8FF;
        border: 1px solid #FFFFFF;
        display: flex;
        align-items: center;
        height: 36px;
        color: #105BDE;
        border-radius: 30px;
        padding: 5px 20px;

        .icon {
          display: flex;
          align-items: center;
          width: 14px;
          height: 16px;

          image {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }

        .order {
          margin-left: 25px;

          text {
            font-size: 14px;
          }

          image {
            width: 6px;
            height: 10px;
            object-fit: contain;
            margin-left: 7px;
          }
        }
      }

      .floated {
        position: absolute;
        bottom: 6%;
        left: 12px;

        .customer,
        .search,
        .position {
          background-size: contain;
        }

        .customer {
          height: 44px;
          width: 44px;
          background-color: #fff;
          background: url(../../static/images/custom.png) 0 0 no-repeat;
          background-size: contain;
        }

        .position {
          height: 44px;
          width: 44px;
          background-color: #fff;
          background: url(../../static/images/locatedCricle.png) 0 0 no-repeat;
          background-size: contain;
        }

        .search {
          height: 44px;
          width: 44px;
          background-color: #fff;
          margin: 15px 0;
          background: url(../../static/images/search.png) 0 0 no-repeat;
          background-size: contain;
        }
      }
    }

    .menu {
      position: fixed;
      left: 0;
      right: 0;
      bottom: 0;
      height: 120px;
      box-sizing: border-box;
      padding: 0 20px 15px 20px;
      display: flex;
      background-color: #ffff;
      border-radius: 0 20px 0 20px;

      .menu-part {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .menu-one {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 8px;

        span {
          width: 45px;
          height: 45px;

          image {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }
        }

        text {
          margin-top: 8rpx;
          font-size: 12px;
          color: #646464;
        }
      }

      .menu-button {
        padding: 12px 20px;
        flex: 1;

        ::v-deep .van-button {
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #255be2;
          color: #fff;
          height: 55px;
          font-size: 18px;
          border-radius: 10px;

          image {
            margin-right: 8px;
            width: 18px;
            height: 18px;
            object-fit: contain;
          }
        }

        ::v-deep .van-button__text {
          display: flex !important;
          align-items: center;
        }
      }
    }

    ::v-deep .van-dialog {
      top: 85% !important;
      width: 90% !important;
    }

    .couponDialog {
      transition: opacity 0.5s ease;

      ::v-deep .van-button {
        width: 100%;
        height: 37px;
        border-radius: 20px;
      }
    }

    .couponDialog.hidden {
      opacity: 0;
    }
  }
</style>
